#!/usr/bin/env python
#coding:utf-8
#__author__="ybh"
import sys,os
import requests
import json
from datetime import datetime
import time
from aliyunsdkcore.client import AcsClient
from aliyunsdkecs.request.v20140526 import DescribeInstancesRequest
basedir = '/'.join(__file__.split("/")[:-2])
sys.path.append(basedir)
os.environ['DJANGO_SETTING_MODULE']='CrazyEye.settings'
from CrazyEye import settings
import django
django.setup()
from web import models

API="https://oapi.dingtalk.com/robot/send?access_token=07133fed0a8d1c70c34c279653967514ced6f3b3de194b5824250218f9034cef"
zone_list=['cn-qingdao','cn-beijing','cn-zhangjiakou','cn-huhehaote','cn-hangzhou','cn-shanghai','cn-shenzhen','cn-hongkong']
def main():
    account_list=models.Account.objects.filter(access_id__isnull=False,product='aliyun').exclude(access_id__exact='')
    for account in account_list:
        if account.access_id and account.access_secret:
            check_expire(account.username,account.access_id,account.access_secret)

def check_expire(username,access_id,access_secret):
    for zone in zone_list:
        client=AcsClient(access_id,access_secret,zone)
        request = DescribeInstancesRequest.DescribeInstancesRequest()
        request.set_PageSize(10)
        response = client.do_action_with_exception(request).decode('utf-8')
        response=json.loads(response)
        if len(response['Instances']['Instance']):
            ins_list=response['Instances']['Instance']
            for ins in ins_list:
                str_time=ins['ExpiredTime']
                expire_time = float(string_toTimestamp(str_time))
                free_time_s = expire_time - float(time.time())

                text=get_text(username,ins['PublicIpAddress']['IpAddress'][0],free_time_s,str_time)
                if text!="":
                    sendToDingtalk(text)




def get_text(account,ip,free_time,expire_time):
    text=""
    if free_time <  60*60*24*15 and free_time >= 60*60*24*14:
        text += "## 服务器\n\n>%s \n\n" % ip
        text += "## 所在阿里云账号\n\n>%s \n\n " % account
        text += "## 到期时间\n\n>%s \n\n" % expire_time.replace('T',' ').replace('Z','')
    elif free_time < 60*60*24*7 and free_time >= 60*60*24*6:
        text += "## 服务器\n\n>%s \n\n" % ip
        text += "## 所在阿里云账号\n\n>%s \n\n " % account
        text += "## 到期时间\n\n>%s \n\n" % expire_time.replace('T',' ').replace('Z','')
    elif free_time < 60*60*24*3 and free_time >= 0:
        text += "## 服务器\n\n>%s \n\n" % ip
        text += "## 所在阿里云账号\n\n>%s \n\n " % account
        text += "## 到期时间\n\n>%s \n\n" % expire_time.replace('T',' ').replace('Z','')
    return text


#把字符串转成datetime
def string_toDatetime(string):
    return datetime.strptime(string, "%Y-%m-%dT%H:%MZ")


#把字符串转成时间戳形式
def string_toTimestamp(strTime):
    return time.mktime(string_toDatetime(strTime).timetuple())


def sendToDingtalk(text):
    headers = {'content-type': 'application/json'}
    parames = {
        "msgtype": "markdown",
        "markdown": {
            "title": "服务器到期提醒",
            "text": text
        },
    }
    parames = json.dumps(parames)
    r = requests.post(API, data=parames, headers=headers)
    return r.text




if __name__=='__main__':
    main()
